package cn.huyanbing.visual.spring.research.ocr;


import org.apache.commons.lang3.math.NumberUtils;
import org.bytedeco.javacpp.*;
import org.bytedeco.opencv.global.opencv_imgcodecs;
import org.bytedeco.opencv.opencv_core.*;

import static org.bytedeco.opencv.global.opencv_imgproc.*;

import org.bytedeco.tesseract.TessBaseAPI;

/**
 * @BelongProject middleware
 * @BelongPackage cn.huyanbing.visual.spring.research.ocr
 * @Description  SpringBoot一键提取身份证与营业执照信息
 *
 * https://mp.weixin.qq.com/s/BTNpcwAq4DzRUt8zCFNAdA
 *
 * @ClassName OCRService
 * @Author huyangbing
 * @Date 2025/1/13 09:35
 * @Version 1.0.0
 */


public class OCRService {

    public String doOCR(String imagePath) {
        TessBaseAPI tessBaseAPI = new TessBaseAPI();

        // 初始化Tesseract
        if (tessBaseAPI.Init(".", "ENG") != 0) {
            System.err.println("Could not initialize Tesseract.");
            return null;
        }

        // 读取图像文件
        Mat image = opencv_imgcodecs.imread(imagePath);
        // 图像预处理
        // 如调整大小、转为灰度图等
        cvtColor(image, image, COLOR_BGR2GRAY);

        //  public native void SetImage(@Cast("const unsigned char*") byte[] imagedata, int width, int height,
        //                  int bytes_per_pixel, int bytes_per_line);
        // 设置图像
        tessBaseAPI.SetImage(image.data(), image.cols(), image.rows(), 1, NumberUtils.toInt(image.step() + ""));

        // 识别文字
        BytePointer outText = tessBaseAPI.GetUTF8Text();
        String result = outText.getString();
        outText.deallocate();

        // 释放资源
        tessBaseAPI.End();

        return result;
    }
}

